"""
镜像更新相关的API端点
"""

from flask import Blueprint, jsonify, request
from flask_socketio import SocketIO
from ..services.image_update_status import get_status_manager
from ..services.config_sync_service import ConfigSyncService
from ..services.gitee_config_service import GiteeConfigService, create_gitee_config_service
import logging
import threading
import os
import json
import time

# 创建专门的详细日志记录器
detailed_logger = logging.getLogger('container_rebuild_detailed')
detailed_logger.setLevel(logging.DEBUG)

# 创建日志目录
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'logs')
os.makedirs(log_dir, exist_ok=True)

# 创建详细日志文件处理器
detailed_log_file = os.path.join(log_dir, 'container_rebuild_detailed.log')
detailed_handler = logging.FileHandler(detailed_log_file, encoding='utf-8')
detailed_handler.setLevel(logging.DEBUG)
detailed_formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
detailed_handler.setFormatter(detailed_formatter)
detailed_logger.addHandler(detailed_handler)

logger = logging.getLogger(__name__)

# 创建蓝图
image_update_bp = Blueprint('image_update', __name__)

def init_image_update_routes(socketio: SocketIO):
    """初始化镜像更新路由，传入socketio实例"""
    
    # 初始化状态管理器
    status_manager = get_status_manager(socketio)
    
    @image_update_bp.route('/api/image-updates/status', methods=['GET'])
    @image_update_bp.route('/api/intelligent-updates/status', methods=['GET'])
    def get_update_status():
        """获取智能更新状态"""
        try:
            status = status_manager.get_status()
            return jsonify({
                "code": 0,
                "data": status,
                "message": "获取状态成功"
            })
        except Exception as e:
            logger.error(f"获取更新状态失败: {e}")
            return jsonify({
                "code": 1,
                "data": None,
                "message": f"获取状态失败: {str(e)}"
            }), 500
    
    @image_update_bp.route('/api/image-updates/check', methods=['POST'])
    @image_update_bp.route('/api/intelligent-updates/check', methods=['POST'])
    def trigger_update_check():
        """手动触发智能更新检查"""
        try:
            data = request.get_json(silent=True) or {}
            force_check = data.get('force', False)
            school_name = data.get('school_name', '测试学校')
            
            logger.info(f"🚀 [API] 收到镜像更新检查请求")
            logger.info(f"📋 [API] 参数: school_name={school_name}, force_check={force_check}")
            
            # 在后台线程执行检查
            def check_updates():
                try:
                    logger.info(f"🔄 [THREAD] 开始后台检查线程")
                    logger.info(f"📝 [THREAD] 手动触发镜像更新检查: {school_name}, 强制检查: {force_check}")
                    
                    # 通知开始检查
                    status_manager.start_checking()
                    logger.info(f"✅ [THREAD] 状态管理器已标记开始检查")
                    
                    # 获取最新的学校配置
                    logger.info(f"🌐 [THREAD] 开始获取学校配置...")
                    gitee_service = create_gitee_config_service()
                    school_config, compose_file_path = gitee_service.fetch_school_config(school_name)
                    logger.info(f"✅ [THREAD] 学校配置获取成功: {school_name}")
                    
                    # 创建配置同步服务并执行检查
                    logger.info(f"🔧 [THREAD] 创建配置同步服务...")
                    sync_service = ConfigSyncService(socketio)
                    logger.info(f"✅ [THREAD] 配置同步服务创建成功")
                    
                    # 执行更新检查
                    logger.info(f"🚀 [THREAD] 开始执行更新检查...")
                    result = sync_service.check_and_update_config(school_config, force_check)
                    logger.info(f"✅ [THREAD] 更新检查完成: {result}")
                    
                    # 通知检查完成
                    status_manager.finish_checking(result)
                    logger.info(f"🏁 [THREAD] 状态管理器已标记检查完成")
                    
                except Exception as e:
                    logger.error(f"❌ [THREAD] 检查过程中发生错误: {e}")
                    status_manager.finish_checking({"error": str(e)})
            
            # 启动后台线程
            thread = threading.Thread(target=check_updates)
            thread.daemon = True
            thread.start()
            logger.info(f"🚀 [API] 后台检查线程已启动")
            
            return jsonify({
                "code": 0,
                "message": "检查已启动",
                "data": {"status": "checking"}
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 触发更新检查失败: {e}")
            return jsonify({
                "code": 1,
                "message": f"启动检查失败: {str(e)}",
                "data": None
            }), 500
    
    @image_update_bp.route('/api/image-updates/startup-check', methods=['POST'])
    @image_update_bp.route('/api/intelligent-updates/startup-check', methods=['POST'])
    def startup_update_check():
        """系统启动时的镜像更新检查"""
        try:
            data = request.get_json(silent=True) or {}
            school_name = data.get('school_name', '测试学校')
            
            logger.info(f"🌅 [API] 收到系统启动检查请求: {school_name}")
            
            # 在后台线程执行启动检查
            def startup_check():
                try:
                    logger.info(f"🌅 [STARTUP] 开始系统启动检查...")
                    
                    # 通知开始检查
                    status_manager.start_checking()
                    
                    # 获取学校配置
                    gitee_service = create_gitee_config_service()
                    school_config, compose_file_path = gitee_service.fetch_school_config(school_name)
                    
                    # 创建配置同步服务并执行启动检查和更新流程
                    sync_service = ConfigSyncService(socketio)
                    result = sync_service.startup_auto_update_check(school_config, silent_mode=True)
                    
                    # 通知检查完成
                    status_manager.finish_checking(result)
                    logger.info(f"✅ [STARTUP] 系统启动检查完成")
                    
                except Exception as e:
                    logger.error(f"❌ [STARTUP] 启动检查失败: {e}")
                    status_manager.finish_checking({"error": str(e)})
            
            # 启动后台线程
            thread = threading.Thread(target=startup_check)
            thread.daemon = True
            thread.start()
            
            return jsonify({
                "code": 0,
                "message": "启动检查已开始",
                "data": {"status": "checking"}
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 系统启动检查失败: {e}")
            return jsonify({
                "code": 1,
                "message": f"启动检查失败: {str(e)}",
                "data": None
            }), 500
    
    @image_update_bp.route('/api/intelligent-updates/lwx-parse', methods=['POST'])
    def lwx_parse_step():
        """LWX平台数据解析步骤"""
        try:
            data = request.get_json(silent=True) or {}
            school_name = data.get('school_name', '测试学校')
            
            logger.info(f"📊 [API] 执行LWX平台数据解析步骤: {school_name}")
            
            # 获取状态管理器，用于发送日志到前端
            status_manager = get_status_manager(socketio)
            status_manager.add_execution_log("info", f"📊 开始LWX平台数据解析: {school_name}")
            
            # 详细信息记录到日志文件
            detailed_logger.info(f"=== LWX平台数据解析开始 (手动模式) ===")
            detailed_logger.info(f"学校名称: {school_name}")
            detailed_logger.info(f"请求参数: {data}")
            detailed_logger.info(f"执行模式: 单步手动执行，不触发配置同步")
            
            # 步骤1: 收集设备信息
            logger.info(f"🔧 [LWX-PARSE] 步骤1: 收集设备信息")
            status_manager.add_execution_log("info", "🔧 收集设备信息")
            
            from ..services.config_sync_service import ConfigSyncService
            sync_service = ConfigSyncService(socketio)
            device_info = sync_service._collect_device_info()
            
            detailed_logger.info(f"设备信息收集结果:")
            detailed_logger.info(f"  主机名: {device_info.get('hostname', 'unknown')}")
            detailed_logger.info(f"  系统平台: {device_info.get('platform', 'unknown')}")
            detailed_logger.info(f"  CPU核心数: {device_info.get('cpu_count', 'unknown')}")
            detailed_logger.info(f"  内存总量: {device_info.get('memory_total', 'unknown')} bytes")
            detailed_logger.info(f"  磁盘总量: {device_info.get('disk_usage', 'unknown')} bytes")
            detailed_logger.info(f"  Docker容器数: {len(device_info.get('docker_containers', []))}")
            
            for i, container in enumerate(device_info.get('docker_containers', [])):
                detailed_logger.info(f"    容器{i+1}: {container.get('name', 'unknown')} - {container.get('status', 'unknown')}")
            
            status_manager.add_execution_log("success", f"✅ 设备信息收集完成: {len(device_info.get('docker_containers', []))} 个容器")
            
            # 步骤2: 上报设备信息到LWX平台
            logger.info(f"📡 [LWX-PARSE] 步骤2: 上报设备信息到LWX平台")
            status_manager.add_execution_log("info", "📡 上报设备信息到LWX平台")
            
            upload_success = sync_service._upload_to_lwx_platform(device_info, trigger_sync=False)
            
            if upload_success:
                logger.info(f"✅ [LWX-PARSE] 设备信息上报成功")
                status_manager.add_execution_log("success", "✅ 设备信息上报成功 (手动模式，未触发配置同步)")
                detailed_logger.info(f"设备信息上报结果: 成功 (手动模式，跳过配置同步)")
            else:
                logger.warning(f"⚠️ [LWX-PARSE] 设备信息上报失败，但继续流程")
                status_manager.add_execution_log("warning", "⚠️ 设备信息上报失败，继续流程")
                detailed_logger.info(f"设备信息上报结果: 失败")
            
            # 步骤3: 从LWX平台获取学校配置
            logger.info(f"🌐 [LWX-PARSE] 步骤3: 从LWX平台获取学校配置")
            status_manager.add_execution_log("info", "🌐 从LWX平台获取学校配置")
            
            lwx_config = sync_service._get_config_from_lwx_platform(school_name)
            
            if lwx_config and "docker" in lwx_config:
                services = lwx_config.get("docker", {}).get("services", [])
                registry = lwx_config.get("docker", {}).get("registry", {})
                
                detailed_logger.info(f"LWX平台配置获取结果:")
                detailed_logger.info(f"  学校名称: {lwx_config.get('school_name', 'unknown')}")
                detailed_logger.info(f"  镜像仓库: {registry.get('url', 'unknown')}")
                detailed_logger.info(f"  服务总数: {len(services)}")
                
                for i, service in enumerate(services):
                    service_name = service.get('name', 'unknown')
                    remote_image = service.get('remote_image', 'unknown')
                    enabled = service.get('enabled', True)
                    port = service.get('port', 'unknown')
                    detailed_logger.info(f"    服务{i+1}: {service_name}")
                    detailed_logger.info(f"      镜像: {remote_image}")
                    detailed_logger.info(f"      端口: {port}")
                    detailed_logger.info(f"      启用: {enabled}")
                
                logger.info(f"✅ [LWX-PARSE] 获取到 {len(services)} 个服务配置")
                status_manager.add_execution_log("success", f"✅ 获取学校配置成功: {len(services)} 个服务")
                
                # 构建服务列表用于后续步骤
                processed_services = []
                for service in services:
                    if service.get('enabled', True):
                        service_name = service.get('name', 'unknown')
                        remote_image = service.get('remote_image', 'unknown')
                        expected_image = f"{registry.get('url', '')}/{remote_image}"
                        
                        processed_services.append({
                            "name": service_name,
                            "remote_image": remote_image,
                            "expected_image": expected_image,
                            "enabled": True,
                            "port": service.get('port', 'unknown'),
                            "auto_update": service.get('auto_update', False)
                        })
                
                # 保存到工作流程JSON文件供后续步骤使用
                workflow_file = "/tmp/manual_steps_workflow.json"
                try:
                    # 读取现有工作流程或创建新的
                    workflow_data = {
                        "workflow_id": "manual_intelligent_update",
                        "created_at": time.time(),
                        "school_name": school_name,
                        "steps": {
                            "step1_lwx_parse": {
                                "status": "completed",
                                "completed_at": time.time(),
                                "data": {
                                    "device_info": {
                                        "hostname": device_info.get('hostname', 'unknown'),
                                        "containers_count": len(device_info.get('docker_containers', [])),
                                        "platform": device_info.get('platform', 'unknown')
                                    },
                                    "lwx_config": lwx_config,
                                    "services": processed_services,
                                    "registry_url": registry.get('url', ''),
                                    "upload_success": upload_success
                                }
                            },
                            "step2_image_verify": {"status": "pending", "completed_at": None, "data": {}},
                            "step3_container_stop": {"status": "pending", "completed_at": None, "data": {}},
                            "step4_config_fetch": {"status": "pending", "completed_at": None, "data": {}},
                            "step5_container_rebuild": {"status": "pending", "completed_at": None, "data": {}}
                        },
                        "summary": {
                            "total_services": len(services),
                            "enabled_services": len(processed_services),
                            "errors": []
                        }
                    }
                    
                    with open(workflow_file, 'w', encoding='utf-8') as f:
                        json.dump(workflow_data, f, ensure_ascii=False, indent=2)
                    
                    detailed_logger.info(f"工作流程数据已保存到: {workflow_file}")
                    detailed_logger.info(f"启用的服务数量: {len(processed_services)}")
                    for i, svc in enumerate(processed_services):
                        detailed_logger.info(f"  服务{i+1}: {svc['name']} -> {svc['expected_image']}")
                    
                    logger.info(f"💾 [LWX-PARSE] 工作流程数据已保存，启用服务: {len(processed_services)}")
                    status_manager.add_execution_log("info", f"💾 工作流程数据已保存供后续步骤使用")
                    
                except Exception as e:
                    logger.warning(f"保存工作流程数据失败: {e}")
                    detailed_logger.error(f"工作流程保存失败: {e}")
                
                # 构建解析结果摘要
                result_data = {
                    "step": "lwx_parse",
                    "status": "completed",
                    "school_name": school_name,
                    "device_info": {
                        "hostname": device_info.get('hostname', 'unknown'),
                        "containers_count": len(device_info.get('docker_containers', [])),
                        "platform": device_info.get('platform', 'unknown')
                    },
                    "lwx_config": {
                        "services_count": len(services),
                        "enabled_services_count": len(processed_services),
                        "registry_url": registry.get('url', 'unknown'),
                        "services": processed_services
                    },
                    "upload_success": upload_success,
                    "workflow_saved": True,
                    "summary": f"解析完成: 学校={school_name}, 设备容器数={len(device_info.get('docker_containers', []))}, 平台服务数={len(services)}, 启用服务数={len(processed_services)}"
                }
                
            else:
                logger.error(f"❌ [LWX-PARSE] 无法获取LWX平台配置")
                status_manager.add_execution_log("error", "❌ 无法获取LWX平台配置")
                detailed_logger.info(f"LWX平台配置获取结果: 失败")
                
                result_data = {
                    "step": "lwx_parse",
                    "status": "failed",
                    "error": "无法获取LWX平台配置",
                    "device_info": {
                        "hostname": device_info.get('hostname', 'unknown'),
                        "containers_count": len(device_info.get('docker_containers', []))
                    }
                }
            
            logger.info(f"📊 [LWX-PARSE] LWX平台数据解析完成")
            status_manager.add_execution_log("success", f"📊 LWX平台数据解析完成: {school_name}")
            detailed_logger.info(f"=== LWX平台数据解析结束 (手动模式) ===")
            
            return jsonify({
                "code": 0,
                "message": "LWX平台数据解析完成",
                "data": result_data
            })
            
        except Exception as e:
            logger.error(f"❌ [API] LWX平台数据解析失败: {e}")
            import traceback
            logger.error(f"❌ [API] 堆栈跟踪: {traceback.format_exc()}")
            
            # 发送错误日志到前端
            try:
                status_manager = get_status_manager(socketio)
                status_manager.add_execution_log("error", f"❌ LWX平台数据解析失败: {str(e)}")
                detailed_logger.error(f"LWX平台数据解析异常详情: {type(e).__name__}: {str(e)}")
            except:
                pass
                
            return jsonify({
                "code": -1,
                "message": f"LWX平台数据解析失败: {str(e)}",
                "data": {"step": "lwx_parse", "status": "failed"}
            }), 500
    
    # 单步执行API端点 (手动模式)
    @image_update_bp.route('/api/intelligent-updates/verify-images', methods=['POST'])
    def verify_images_step():
        """镜像版本校验步骤 - 基于第1步的结果"""
        try:
            data = request.get_json(silent=True) or {}
            
            # 获取状态管理器
            status_manager = get_status_manager(socketio)
            status_manager.add_execution_log("info", "🔍 开始镜像版本校验")
            
            # 详细信息记录到日志文件
            detailed_logger.info(f"=== 镜像版本校验开始 (手动模式) ===")
            
            # 尝试从工作流程JSON文件读取第1步的结果
            workflow_file = "/tmp/manual_steps_workflow.json"
            school_name = None
            step1_data = None
            
            try:
                if os.path.exists(workflow_file):
                    with open(workflow_file, 'r', encoding='utf-8') as f:
                        workflow_data = json.load(f)
                    
                    if workflow_data.get("steps", {}).get("step1_lwx_parse", {}).get("status") == "completed":
                        step1_data = workflow_data["steps"]["step1_lwx_parse"]["data"]
                        school_name = workflow_data.get("school_name")
                        
                        logger.info(f"📋 [VERIFY] 读取到第1步数据: 学校={school_name}")
                        status_manager.add_execution_log("info", f"📋 基于第1步数据: {school_name}")
                        detailed_logger.info(f"第1步数据读取成功: 学校={school_name}")
                    else:
                        logger.warning(f"⚠️ [VERIFY] 第1步未完成，使用请求参数")
                        school_name = data.get('school_name', '测试学校')
                else:
                    logger.warning(f"⚠️ [VERIFY] 工作流程文件不存在，使用请求参数")
                    school_name = data.get('school_name', '测试学校')
                    
            except Exception as e:
                logger.warning(f"⚠️ [VERIFY] 读取工作流程文件失败: {e}")
                school_name = data.get('school_name', '测试学校')
            
            logger.info(f"🔍 [API] 执行镜像版本校验步骤: {school_name}")
            detailed_logger.info(f"学校名称: {school_name}")
            
            # 从Gitee获取该学校的完整配置
            service = ConfigSyncService(socketio)
            logger.info(f"📡 [API] 从Gitee获取配置: {school_name}")
            status_manager.add_execution_log("info", "📡 从Gitee获取学校完整配置")
            
            gitee_service = create_gitee_config_service()
            school_config, compose_path = gitee_service.fetch_school_config(school_name)

            if not school_config or "docker" not in school_config:
                status_manager.add_execution_log("error", "❌ 无法获取学校的Docker配置")
                detailed_logger.error(f"学校配置获取失败: {school_name}")
                return jsonify({
                    "code": -1,
                    "message": "无法获取学校的Docker配置（Gitee）",
                    "data": {"step": "verify_images", "status": "failed"}
                }), 500
            
            services = school_config["docker"].get("services", [])
            registry_url = school_config["docker"].get("registry", {}).get("url", "")
            detailed_logger.info(f"学校配置获取成功:")
            detailed_logger.info(f"  镜像仓库: {registry_url}")
            detailed_logger.info(f"  服务总数: {len(services)}")
            
            # 执行镜像校验
            logger.info(f"🔍 [API] 开始校验镜像版本...")
            status_manager.add_execution_log("info", f"🔍 开始校验 {len(services)} 个服务的镜像版本")
            image_verification_results = []
            
            for service_config in school_config["docker"].get("services", []):
                if service_config.get("enabled", True):
                    service_name = service_config["name"]
                    remote_image = service_config["remote_image"]
                    registry_url = school_config["docker"].get("registry", {}).get("url", "")
                    expected_image = f"{registry_url}/{remote_image}"
                    
                    logger.info(f"🔍 [API] 校验服务: {service_name} -> {expected_image}")
                    status_manager.add_execution_log("info", f"🔍 校验服务: {service_name}")
                    
                    # 检查镜像是否存在且版本是否正确
                    needs_action, action_type, reason = service._verify_image_version(expected_image)
                    
                    # 详细日志记录
                    detailed_logger.info(f"服务校验结果:")
                    detailed_logger.info(f"  服务名: {service_name}")
                    detailed_logger.info(f"  期望镜像: {expected_image}")
                    detailed_logger.info(f"  需要操作: {needs_action}")
                    detailed_logger.info(f"  操作类型: {action_type}")
                    detailed_logger.info(f"  原因: {reason}")
                    
                    result = {
                        "service": service_name,
                        "image": expected_image,
                        "needs_action": needs_action,
                        "action_type": action_type,  # 'update', 'replace', 'none'
                        "reason": reason
                    }
                    image_verification_results.append(result)
                    logger.info(f"🔍 [API] {service_name}: {action_type} - {reason}")
                    
                    # 发送校验结果到前端
                    if needs_action:
                        status_manager.add_execution_log("warning", f"⚠️ {service_name}: {reason}")
                    else:
                        status_manager.add_execution_log("success", f"✅ {service_name}: 镜像版本正确")
            
            # 统计结果
            needs_update = [r for r in image_verification_results if r["needs_action"]]
            up_to_date = [r for r in image_verification_results if not r["needs_action"]]
            
            logger.info(f"✅ [API] 镜像版本校验完成，需要处理的服务数量: {len(needs_update)}")
            status_manager.add_execution_log("success", f"✅ 镜像版本校验完成: {len(needs_update)}/{len(image_verification_results)} 个服务需要处理")
            detailed_logger.info(f"=== 镜像版本校验结束 (手动模式) ===")
            detailed_logger.info(f"校验结果统计: 总服务数={len(image_verification_results)}, 需要处理={len(needs_update)}")
            
            # 更新工作流程JSON文件
            try:
                if os.path.exists(workflow_file):
                    with open(workflow_file, 'r', encoding='utf-8') as f:
                        workflow_data = json.load(f)
                else:
                    workflow_data = {"steps": {}}
                
                # 更新第2步的数据
                workflow_data["steps"]["step2_image_verify"] = {
                    "status": "completed",
                    "completed_at": time.time(),
                    "data": {
                        "verification_results": image_verification_results,
                        "services_need_action": needs_update,
                        "services_up_to_date": up_to_date,
                        "school_config": school_config
                    }
                }
                
                with open(workflow_file, 'w', encoding='utf-8') as f:
                    json.dump(workflow_data, f, ensure_ascii=False, indent=2)
                    
                detailed_logger.info(f"第2步结果已保存到工作流程文件")
                
            except Exception as e:
                logger.warning(f"保存工作流程数据失败: {e}")
            
            return jsonify({
                "code": 0,
                "message": "镜像版本校验完成",
                "data": {
                    "step": "verify_images",
                    "status": "completed",
                    "details": f"校验完成，发现 {len(needs_update)} 个服务需要处理",
                    "verification_results": image_verification_results,
                    "services_need_action": needs_update,
                    "services_up_to_date": up_to_date,
                    "summary": {
                        "total_services": len(image_verification_results),
                        "need_action": len(needs_update),
                        "up_to_date": len(up_to_date)
                    }
                }
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 镜像校验步骤失败: {e}")
            import traceback
            logger.error(f"❌ [API] 堆栈跟踪: {traceback.format_exc()}")
            detailed_logger.error(f"镜像校验异常详情: {type(e).__name__}: {str(e)}")
            return jsonify({
                "code": -1,
                "message": f"镜像校验失败: {str(e)}",
                "data": {"step": "verify_images", "status": "failed"}
            }), 500
    
    @image_update_bp.route('/api/intelligent-updates/stop-containers', methods=['POST'])
    def stop_containers_step():
        """容器停止和清理步骤"""
        try:
            data = request.get_json(silent=True) or {}
            school_name = data.get('school_name', '测试学校')
            services_to_stop = data.get('services', [])
            
            logger.info(f"🛑 [API] 执行容器停止和清理步骤: {school_name}")
            logger.info(f"📋 [API] 需要停止的服务: {services_to_stop}")
            
            # 实际的容器停止逻辑
            service = ConfigSyncService(socketio)
            stopped_services = []
            cleaned_images = []
            
            # 如果没有指定服务列表，从Gitee获取配置并构建服务列表
            if not services_to_stop:
                logger.info(f"📡 [API] 未指定服务列表，从Gitee获取配置...")
                gitee_service = create_gitee_config_service()
                school_config, _ = gitee_service.fetch_school_config(school_name)
                if school_config and "docker" in school_config:
                    for service_config in school_config["docker"].get("services", []):
                        if service_config.get("enabled", True):
                            services_to_stop.append(service_config.get("name"))
            
            # 停止和清理每个服务
            for service_name in services_to_stop:
                try:
                    logger.info(f"🛑 [API] 停止容器: {service_name}")
                    service._stop_container_if_running(service_name)
                    stopped_services.append(service_name)
                    
                    # 可选：清理旧镜像
                    logger.info(f"🗑️ [API] 清理镜像: {service_name}")
                    service._remove_old_image(service_name)
                    cleaned_images.append(service_name)
                    
                except Exception as e:
                    logger.warning(f"⚠️ [API] 停止/清理服务 {service_name} 时出错: {e}")
            
            logger.info(f"✅ [API] 容器停止和清理完成")
            
            return jsonify({
                "code": 0,
                "message": "容器停止和清理完成",
                "data": {
                    "step": "stop_containers",
                    "status": "completed",
                    "details": f"已停止 {len(stopped_services)} 个容器，清理 {len(cleaned_images)} 个镜像",
                    "stopped_services": stopped_services,
                    "cleaned_images": cleaned_images
                }
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 容器停止步骤失败: {e}")
            import traceback
            logger.error(f"❌ [API] 堆栈跟踪: {traceback.format_exc()}")
            return jsonify({
                "code": -1,
                "message": f"容器停止失败: {str(e)}",
                "data": {"step": "stop_containers", "status": "failed"}
            }), 500
    
    @image_update_bp.route('/api/intelligent-updates/fetch-config', methods=['POST'])
    def fetch_config_step():
        """Gitee配置拉取步骤"""
        try:
            data = request.get_json(silent=True) or {}
            school_name = data.get('school_name', '测试学校')
            
            logger.info(f"📥 [API] 收到Gitee配置拉取请求")
            logger.info(f"🏫 [API] 学校名称: {school_name}")
            logger.info(f"📋 [API] 请求数据: {data}")
            
            # 实际的配置拉取逻辑
            logger.info(f"🔧 [API] 创建GiteeConfigService实例...")
            gitee_service = create_gitee_config_service()
            
            logger.info(f"📡 [API] 开始从Gitee拉取配置...")
            school_config, compose_file_path = gitee_service.fetch_school_config(school_name)
            
            logger.info(f"✅ [API] 配置拉取成功")
            logger.info(f"📁 [API] Compose文件路径: {compose_file_path}")
            logger.info(f"📊 [API] 配置内容键: {list(school_config.keys()) if school_config else 'None'}")
            
            result_data = {
                "step": "fetch_config",
                "status": "completed",
                "details": f"配置文件已拉取: {school_name}",
                "config_path": compose_file_path,
                "school_name": school_name,
                "config_keys": list(school_config.keys()) if school_config else []
            }
            
            logger.info(f"📤 [API] 返回响应数据: {result_data}")
            
            return jsonify({
                "code": 0,
                "message": "Gitee配置拉取完成",
                "data": result_data
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 配置拉取步骤失败: {e}")
            logger.error(f"❌ [API] 异常类型: {type(e).__name__}")
            logger.error(f"❌ [API] 异常详情: {str(e)}")
            import traceback
            logger.error(f"❌ [API] 堆栈跟踪: {traceback.format_exc()}")
            
            return jsonify({
                "code": -1,
                "message": f"配置拉取失败: {str(e)}",
                "data": {
                    "error": str(e),
                    "error_type": type(e).__name__
                }
            }), 500
    
    @image_update_bp.route('/api/intelligent-updates/rebuild-containers', methods=['POST'])
    def rebuild_containers_step():
        """容器服务重建步骤"""
        try:
            data = request.get_json(silent=True) or {}
            school_name = data.get('school_name', '测试学校')
            
            logger.info(f"🔨 [API] 执行容器服务重建步骤: {school_name}")
            
            # 获取状态管理器，用于发送日志到前端
            status_manager = get_status_manager(socketio)
            status_manager.add_execution_log("info", f"🔨 开始容器服务重建: {school_name}")
            
            # 详细信息记录到日志文件
            detailed_logger.info(f"=== 容器服务重建开始 ===")
            detailed_logger.info(f"学校名称: {school_name}")
            detailed_logger.info(f"请求参数: {data}")
            
            # 实际的容器重建逻辑（使用缓存的配置，避免重复拉取）
            service = ConfigSyncService(socketio)
            status_manager.add_execution_log("info", "🔧 初始化配置同步服务")
            
            detailed_logger.info(f"项目根目录: {service.project_root}")
            detailed_logger.info(f"配置目录: {service.config_dir}")
            detailed_logger.info(f"Docker客户端状态: {'已连接' if service.docker_client else '未连接'}")
            
            # 首先尝试从缓存获取配置
            cached_config_file = f"/tmp/gitee_configs/{school_name}.json"
            detailed_logger.info(f"检查缓存配置文件: {cached_config_file}")
            
            if os.path.exists(cached_config_file):
                logger.info(f"📋 [API] 使用缓存的配置文件: {cached_config_file}")
                status_manager.add_execution_log("info", "📋 使用缓存的配置文件")
                detailed_logger.info(f"缓存文件路径: {cached_config_file}")
                
                try:
                    with open(cached_config_file, 'r', encoding='utf-8') as f:
                        school_config = json.load(f)
                    compose_file_path = f"/tmp/gitee_configs/docker-compose-{school_name}.yml"
                    
                    # 详细配置信息写入日志文件
                    if school_config:
                        config_keys = list(school_config.keys())
                        detailed_logger.info(f"配置文件键: {config_keys}")
                        if "docker" in school_config:
                            docker_config = school_config["docker"]
                            if "services" in docker_config:
                                services = docker_config["services"]
                                service_count = len(services)
                                detailed_logger.info(f"Docker服务数量: {service_count}")
                                for i, svc in enumerate(services):
                                    service_name = svc.get("name", "未知")
                                    remote_image = svc.get("remote_image", "未知")
                                    enabled = svc.get("enabled", True)
                                    port = svc.get("port", "未知")
                                    detailed_logger.info(f"  服务{i+1}: {service_name}")
                                    detailed_logger.info(f"    镜像: {remote_image}")
                                    detailed_logger.info(f"    端口: {port}")
                                    detailed_logger.info(f"    启用: {enabled}")
                            if "registry" in docker_config:
                                registry = docker_config["registry"]
                                detailed_logger.info(f"镜像仓库配置: {registry}")
                        
                        # 前端只显示摘要信息
                        if "docker" in school_config and "services" in school_config["docker"]:
                            service_count = len(school_config["docker"]["services"])
                            status_manager.add_execution_log("info", f"📊 发现 {service_count} 个Docker服务配置")
                    
                except Exception as e:
                    logger.warning(f"读取缓存配置失败: {e}，重新拉取")
                    status_manager.add_execution_log("warning", f"⚠️ 读取缓存配置失败，重新拉取")
                    detailed_logger.error(f"缓存读取错误详情: {type(e).__name__}: {str(e)}")
                    school_config = None
            else:
                logger.info(f"📡 [API] 缓存不存在，从Gitee获取配置: {school_name}")
                status_manager.add_execution_log("info", "📡 缓存不存在，从Gitee获取配置")
                detailed_logger.info(f"缓存文件不存在: {cached_config_file}")
                school_config = None
            
            # 如果缓存不存在或读取失败，才重新拉取
            if not school_config:
                status_manager.add_execution_log("info", "📡 从Gitee重新拉取配置")
                gitee_service = create_gitee_config_service()
                school_config, compose_file_path = gitee_service.fetch_school_config(school_name)

            if not school_config:
                error_msg = "无法获取学校配置（Gitee）"
                status_manager.add_execution_log("error", f"❌ {error_msg}")
                return jsonify({
                    "code": -1,
                    "message": error_msg,
                    "data": {"step": "rebuild_containers", "status": "failed"}
                }), 500

            # 从远程同步docker-compose文件（不再本地生成）
            logger.info(f"📝 [API] 从远程同步docker-compose文件...")
            status_manager.add_execution_log("info", "📝 从远程同步docker-compose文件")
            try:
                service._generate_docker_compose_file(school_name, school_config)
                status_manager.add_execution_log("success", "✅ Docker Compose文件同步成功")
            except Exception as e:
                logger.error(f"❌ [API] 从远程获取Docker Compose文件失败: {e}")
                status_manager.add_execution_log("error", f"❌ Docker Compose文件同步失败: {str(e)}")
                return jsonify({
                    "code": -1,
                    "message": f"无法获取Docker Compose文件: {str(e)}",
                    "data": {"step": "rebuild_containers", "status": "failed"}
                }), 500
            
            # 启动Docker服务
            logger.info(f"🚀 [API] 启动Docker服务...")
            status_manager.add_execution_log("info", "🚀 启动Docker服务")
            try:
                service._start_docker_services(school_name)
                logger.info(f"✅ [API] 容器服务重建完成")
                status_manager.add_execution_log("success", f"✅ 容器服务重建完成: {school_name}")
            except Exception as e:
                logger.error(f"❌ [API] 启动Docker服务失败: {e}")
                status_manager.add_execution_log("error", f"❌ 启动Docker服务失败: {str(e)}")
                return jsonify({
                    "code": -1,
                    "message": f"启动Docker服务失败: {str(e)}",
                    "data": {"step": "rebuild_containers", "status": "failed"}
                }), 500
            
            return jsonify({
                "code": 0,
                "message": "容器服务重建完成",
                "data": {
                    "step": "rebuild_containers",
                    "status": "completed",
                    "details": f"基于Gitee配置重建容器服务完成: {school_name}",
                    "school_name": school_name,
                    "compose_file": compose_file_path
                }
            })
            
        except Exception as e:
            logger.error(f"❌ [API] 容器重建步骤失败: {e}")
            import traceback
            logger.error(f"❌ [API] 堆栈跟踪: {traceback.format_exc()}")
            
            # 发送错误日志到前端
            try:
                status_manager = get_status_manager(socketio)
                status_manager.add_execution_log("error", f"❌ 容器重建失败: {str(e)}")
            except:
                pass  # 避免日志记录失败影响错误响应
                
            return jsonify({
                "code": -1,
                "message": f"容器重建失败: {str(e)}",
                "data": {"step": "rebuild_containers", "status": "failed"}
            }), 500
    
    # 注册WebSocket事件
    @socketio.on('connect', namespace='/updates')
    def handle_connect():
        """客户端连接"""
        logger.info("客户端连接到更新状态频道")
        # 发送当前状态
        current_status = get_status_manager().get_status()
        socketio.emit('update_status', current_status, namespace='/updates')

    @socketio.on('disconnect', namespace='/updates')
    def handle_disconnect():
        """客户端断开连接"""
        logger.info("客户端断开更新状态频道")
    
    return image_update_bp